import flask
from flask import Blueprint
import db
import datetime

page_upload = Blueprint('page_upload', __name__)


@page_upload.route('/upload_<op>', methods=['GET', 'POST'])
def upload(op):
    """
    upload goods page
    :param op: add new item - new, update existing item - update
    :return: null
    """
    if flask.request.method == 'GET':
        if op == 'new':
            return flask.render_template('./static/templates/upload.html', origin=None)
        else:
            gid = op.split('_')
            goods, cmt = db.get_item_info(int(gid[1]))
            return flask.render_template('./static/templates/upload.html', origin=goods)
    if flask.request.method == 'POST':
        name = flask.request.form.get('name')
        price = flask.request.form.get('price')
        des = flask.request.form.get('des')
        uploader = flask.request.form.get('uploader')

        if op == 'new':
            f_img = flask.request.files.get('img')
            f_img_name = f_img.filename
            t = datetime.datetime.now().strftime('%Y-%m-%d-%H-%M-%S')
            full_path = 'static/img/' + t + '-' + f_img_name
            print(name, price, des, f_img_name)
            try:
                f_img.save(full_path)
                db.insert_goods(name, price, des, '../' + full_path, uploader, flask.request.form.get('gid'))
            except Exception as e:
                print(e)
                return 'Error: fail to save file.'
            finally:
                return flask.redirect('/')

        if op == 'update':
            f_img = flask.request.files.get('img')
            f_img_name = f_img.filename
            if f_img_name != '':
                t = datetime.datetime.now().strftime('%Y-%m-%d-%H-%M-%S')
                full_path = 'static/img/' + t + '-' + f_img_name
                print('['+f_img_name+']', type(f_img_name))
                try:
                    f_img.save(full_path)
                    db.insert_goods(name, price, des, '../' + full_path, uploader, flask.request.form.get('gid'))
                except Exception as e:
                    print(e)
                    return 'Error: fail to save file.'
                finally:
                    return flask.redirect('/')
            else:
                db.insert_goods(name, price, des, '', uploader, flask.request.form.get('gid'))
        return '404 Not Found.'
